package com.thank.concurrency.samples.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 演示CountDownLatch普通用法
 * await()超过某个时间这个任务就不继续等待了
 */
@Slf4j
public class CountDownLatchExample2 {

    private final static int threadCount = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            // 注意: 放在这里没有用的，因为这时候还是在主线程中阻塞，阻塞完以后才开始执行下面的await
            // Thread.sleep(1);
            exec.execute(() -> {
                try {
                    test(threadNum);
                } catch (Exception e) {
                    log.info("exception:", e);
                } finally {
                    // 一般为防止出现异常，放在finally更保险一些
                    countDownLatch.countDown();
                }
            });
        }

        // 指定等待的时间(超过某个时间这个任务就不继续等待了)
        // 参数1: 等待时间, 参数2: 时间单位
        countDownLatch.await(50, TimeUnit.MILLISECONDS);
        log.info("finished!"); // 会输出在最前面, 然后输出其他线程的test方法log

        // 注意: 这个并不是第一时间内销毁掉所有线程，而是先让正在执行线程执行完
        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        Thread.sleep(100);
        log.info("{}", threadNum);
    }
}
